<template>
  <div class='u-class-dialog'>
    <el-dialog
      title="输入子级分类信息"
      :visible.sync="dialogVisible"
      :before-close="handleClose">
      <el-form class="form" ref='form' label-width="130px" :model="form" :rules='rules'>
        <el-form-item label="子级分类名称：" prop='name'>
          <el-input type="text" placeholder="输入子级分类名称" v-model.trim="form.name"></el-input>
        </el-form-item>
        <el-form-item align='right'>
          <el-button type="primary" @click="handleClose">取消</el-button>
          <el-button type="primary" @click="confirm">{{ openType === 'add' ? '确认' : '修改' }}</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'uClass-dialog',

  props: ['openType'],

  data() {
    return {
      dialogVisible: false,
      form: {
        name: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入子级分类名称', trigger: 'blur' },
          { max: 18, min: 1, message: '长度为 1 - 18 个字符', trigger: 'blur' }
        ]
      },
      ifRequesting: false,
      id: ''
    }
  },

  mounted() {
  },

  methods: {

    confirm() {
      if (this.ifRequesting) return
      this.$refs.form.validate((valid) => {
        if (!valid) return
        this.request()
      })
    },

    async request() {
      this.ifRequesting = true
      const openType = this.openType === 'add'
      const form = this.form
      const { code, data } = await this.$api[openType ? 'utilsCreateClass' : 'utilsUpdateClass']({
        aAttributeId: this.$route.query.attrId,
        aClassId: this.$route.query.id,
        aName: form.name,
        aId: this.id || ''
      })
      this.ifRequesting = false
      if (code === 0) {
        this.dialogVisible = false
        this.__notify(openType ? '添加分类' : '修改分类')
        this.$emit('close', true, openType ? data.id : '')
      }
    },

    reset() {
      this.$nextTick(() => {
        if (!this.$refs.form) return false
        this.id = ''
        this.$refs.form.resetFields()
      })
    },

    handleClose() {
      this.dialogVisible = false
      this.$emit('close')
    },

    async getAttr(aId) {
      const { code, data } = await this.$api.utilsGetClassById({ aId })
      if (code === 0) {
        this.form.name = data.name
      }
    },

    async __show(type, id) {
      this.reset()
      if (type === 'modify') {
        await this.getAttr(id)
        this.id = id
      }
      this.dialogVisible = true
    }
  }
}
</script>

<style lang='less'>
</style>